package org.example.mapping;

import java.util.ArrayList;
import java.util.List;

public class BoundSql {

    private final String sql;

    private final Object parameterObject;


    private  String finalSql;


    private List<String> parameterNames;



    private final List<ParameterMapping> parameterMappings;


    public BoundSql(String sql, Object parameterObject,List<ParameterMapping> parameterMappings) {
        this.sql = sql;
        this.parameterObject = parameterObject;
        this.parameterMappings = parameterMappings;
        this.buildSql(sql);
    }



    public String getBuildSql() {
        return finalSql;
    }
        




    
    



    private  void buildSql(String sql) {
        StringBuilder builder = new StringBuilder();
        List<String> list = new ArrayList<>();
        int length = sql.length();

        char[] chars = sql.toCharArray();
        int tokenEnd = -1;
        for (int i = 0; i < length; i++) {
            char aChar = chars[i];
            if(aChar == '#' && chars[ i + 1] == '{') {
                 int s1 = i + 2;
                 StringBuilder parameterName = new StringBuilder();
                for (int j = s1; j < length; j++) {
                    char aChar1 = chars[j];
                    if(aChar1 == '}') {
                        builder.append('?');
                        tokenEnd = j + 1;
                        break;
                    }else {
                        parameterName.append(aChar1);
                    }
                }
                list.add(parameterName.toString());
            }

            if(i >= tokenEnd) {
                builder.append(aChar);
            }
        }

        this.finalSql = builder.toString();
        this.parameterNames = list;



    }



    public String getSql() {
        return sql;
    }

    public Object getParameterObject() {
        return parameterObject;
    }

    public List<ParameterMapping> getParameterMappings() {
        return parameterMappings;
    }
}
